// 添加API基础URL
const API_BASE_URL = 'http://localhost:5000';

// DOM元素
const tableBody = document.getElementById('department-table-body');
const departmentCountElement = document.getElementById('department-count');
const currentTimeElement = document.getElementById('current-time');
const addDepartmentBtn = document.getElementById('add-department-btn');
const refreshBtn = document.getElementById('refresh-btn');
const departmentModal = document.getElementById('department-modal');
const modalTitle = document.getElementById('modal-title');
const departmentNameInput = document.getElementById('department-name');
const closeModalBtn = document.getElementById('close-modal');
const cancelBtn = document.getElementById('cancel-btn');
const saveBtn = document.getElementById('save-btn');
const toast = document.getElementById('toast');

// 当前编辑的部门ID
let currentDepartmentId = null;
let departmentsData = []; // 存储当前的部门数据

// 初始化函数
async function init() {
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000);

    await fetchDepartments();

    // 添加事件监听
    addDepartmentBtn.addEventListener('click', () => openModal('add'));
    refreshBtn.addEventListener('click', fetchDepartments);
    closeModalBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);
    saveBtn.addEventListener('click', saveDepartment);

    // 添加表格事件委托监听器
    addTableEventListeners();
}

// 添加表格事件委托监听器
function addTableEventListeners() {
    // 使用事件委托处理按钮点击
    tableBody.addEventListener('click', handleTableClick);
}

// 表格点击事件处理函数
function handleTableClick(event) {
    // 确定实际点击的元素
    let targetElement = event.target;

    // 如果是图标元素，则查找其父按钮元素
    if (targetElement.tagName === 'I') {
        targetElement = targetElement.closest('button');
    }

    // 如果点击的是编辑按钮
    if (targetElement.classList.contains('edit-btn') || targetElement.classList.contains('fa-edit')) {
        // 获取部门ID
        const departmentId = targetElement.dataset.id;
        // 查找对应的部门对象
        const department = departmentsData.find(d => d.id == departmentId);
        if (department) {
            console.log(`编辑部门: ${department.name}`);
            openModal('edit', department);
        }
        return;
    }

    // 如果点击的是删除按钮
    if (targetElement.classList.contains('delete-btn') || targetElement.classList.contains('fa-trash-alt')) {
        // 获取部门ID
        const departmentId = targetElement.dataset.id;
        // 查找对应的部门对象
        const department = departmentsData.find(d => d.id == departmentId);
        if (department) {
            console.log(`删除部门: ${department.name}`);
            deleteDepartment(department);
        }
        return;
    }
}

// 更新当前系统时间
function updateCurrentTime() {
    const now = new Date();
    const timeStr = now.toLocaleTimeString('zh-CN');
    const dateStr = now.toLocaleDateString('zh-CN');
    currentTimeElement.textContent = `${dateStr} ${timeStr}`;
}

// 初始化页面
document.addEventListener('DOMContentLoaded', init);

// 从后端获取部门数据
async function fetchDepartments() {
    // 显示加载状态
    tableBody.innerHTML = `
        <tr>
            <td colspan="4">
                <div class="loader-container">
                    <div class="loader"></div>
                </div>
            </td>
        </tr>
    `;

    try {
        // 使用Fetch API获取真实数据
        const response = await fetch(`${API_BASE_URL}/api/departments`);

        // 检查响应状态
        if (!response.ok) {
            throw new Error(`HTTP错误! 状态: ${response.status}`);
        }

        // 尝试解析JSON
        const result = await response.json();

        // 检查后端返回的code字段
        if (result.code === 200) {
            // 保存数据到全局变量
            departmentsData = result.data;
            renderDepartments(departmentsData);
        } else {
            throw new Error(result.msg || `后端错误: ${result.code}`);
        }

    } catch (error) {
        // 详细的错误处理
        console.error('获取数据失败:', error);
        tableBody.innerHTML = `
            <tr>
                <td colspan="4">
                    <div class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        数据加载失败: ${error.message || '未知错误，请刷新页面重试'}
                    </div>
                </td>
            </tr>
        `;
    }
}

// 渲染部门数据到表格
function renderDepartments(departments) {
    if (!departments || departments.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="4">
                    <div class="empty-state">
                        <i class="fas fa-inbox"></i>
                        <h3>暂无部门数据</h3>
                        <p>请点击"新增部门"按钮添加部门信息</p>
                    </div>
                </td>
            </tr>
        `;
        departmentCountElement.textContent = '0';
        return;
    }

    // 构建表格行的HTML
    const rowsHTML = departments.map((dept, index) => {
        // 使用 updateTime 字段，如果不存在则使用 createTime
        const timeField = dept.updateTime || dept.createTime || '未知时间';

        return `
            <tr>
                <td>${index + 1}</td>
                <td><strong>${dept.name}</strong></td>
                <td>${timeField}</td>
                <td class="actions-cell">
                    <button class="btn btn-edit edit-btn" data-id="${dept.id}">
                        <i class="fas fa-edit"></i>
                        编辑
                    </button>
                    <button class="btn btn-delete delete-btn" data-id="${dept.id}">
                        <i class="fas fa-trash-alt"></i>
                        删除
                    </button>
                </td>
            </tr>
        `;
    }).join('');

    tableBody.innerHTML = rowsHTML;
    departmentCountElement.textContent = departments.length;

    // 添加视觉反馈，确认按钮渲染成功
    if (document.querySelector('.edit-btn')) {
        console.log("编辑按钮已成功渲染");
    }
    if (document.querySelector('.delete-btn')) {
        console.log("删除按钮已成功渲染");
    }
}

// 打开模态框
function openModal(action, department = null) {
    if (action === 'add') {
        modalTitle.textContent = '添加新部门';
        departmentNameInput.value = '';
        currentDepartmentId = null;
    } else if (action === 'edit' && department) {
        modalTitle.textContent = '编辑部门';
        departmentNameInput.value = department.name;
        currentDepartmentId = department.id;
    }

    departmentModal.style.display = 'flex';

    // 设置输入框焦点
    setTimeout(() => {
        departmentNameInput.focus();
    }, 100);
}

// 关闭模态框
function closeModal() {
    departmentModal.style.display = 'none';
}

// 保存部门（添加或编辑）
async function saveDepartment() {
    const name = departmentNameInput.value.trim();

    if (!name) {
        showToast('部门名称不能为空', 'error');
        return;
    }

    try {
        let url, method;

        if (currentDepartmentId) {
            // 编辑现有部门
            url = `${API_BASE_URL}/api/departments/${currentDepartmentId}`;
            method = 'PUT';
        } else {
            // 添加新部门
            url = `${API_BASE_URL}/api/departments`;
            method = 'POST';
        }

        // 显示保存中的状态
        const originalButtonText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        saveBtn.disabled = true;

        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name: name })
        });

        // 恢复按钮状态
        saveBtn.innerHTML = originalButtonText;
        saveBtn.disabled = false;

        // 检查响应状态
        if (!response.ok) {
            const errorResponse = await response.text();
            throw new Error(`HTTP错误! 状态: ${response.status}\n响应: ${errorResponse}`);
        }

        const result = await response.json();

        if (result.code === 200) {
            showToast(
                currentDepartmentId ? '部门更新成功' : '部门添加成功',
                'success'
            );
            closeModal();
            fetchDepartments();
        } else {
            throw new Error(result.msg || '操作失败');
        }

    } catch (error) {
        console.error('保存失败:', error);
        showToast(error.message || '操作失败，请重试', 'error');
    }
}

// 删除部门
async function deleteDepartment(dept) {
    const confirmDelete = confirm(`确定要删除 "${dept.name}" 部门吗？此操作不可恢复。`);
    if (!confirmDelete) return;

    try {
        // 在API请求前禁用删除按钮
        const deleteButton = document.querySelector(`.delete-btn[data-id="${dept.id}"]`);
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 删除中...';
        }

        const response = await fetch(`${API_BASE_URL}/api/departments/${dept.id}`, {
            method: 'DELETE'
        });

        // 恢复按钮状态
        if (deleteButton) {
            deleteButton.disabled = false;
            deleteButton.innerHTML = '<i class="fas fa-trash-alt"></i> 删除';
        }

        // 检查响应状态
        if (!response.ok) {
            const errorResponse = await response.text();
            throw new Error(`HTTP错误! 状态: ${response.status}\n响应: ${errorResponse}`);
        }

        const result = await response.json();

        if (result.code === 200) {
            showToast('部门删除成功', 'success');
            // 从数组中移除已删除的部门
            departmentsData = departmentsData.filter(d => d.id != dept.id);
            renderDepartments(departmentsData);
        } else {
            throw new Error(result.msg || '删除失败');
        }

    } catch (error) {
        console.error('删除失败:', error);
        showToast(error.message || '删除失败，请重试', 'error');
    }
}

// 显示通知提示
function showToast(message, type) {
    toast.textContent = message;
    toast.className = `toast toast-${type}`;
    toast.classList.add('show');

    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}